package com.huynhchihieu.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Repository;

import com.huynhchihieu.domain.Domainuser;

@Repository
public class UserDAOImpl implements UserDAO {

	@PersistenceContext(unitName = "persistenceUnit")
	private EntityManager entityManager;
	
	

	@Autowired
	private SessionFactory sessionFactory;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	
	public Domainuser getUserByEmail(String email) {
		List<Domainuser> userList = entityManager
				.createNativeQuery("select *from domainuser where user_email = ?", Domainuser.class).setParameter(1, email)
				.getResultList();
		if (userList.size() > 0)
			return userList.get(0);
		else
			return null;
	}
	
	public Domainuser getUserBySessionFactory(String login) {
		// List<Domainuser> userList = sessionFactory.getCurrentSession()
		// .createSQLQuery("select *from domainuser where login = ?").setParameter(1,
		// login).list();
		List<Domainuser> userList = sessionFactory.getCurrentSession().createCriteria(Domainuser.class)
				.add(Restrictions.eq("login", login)).list();
		if (userList.size() > 0) {
			return userList.get(0);
		} else {
			return null;
		}
	}

	public Domainuser createUser(Domainuser user) {
//		String hashedPassword = passwordEncoder.encode(user.getPassword());
//		user.setPassword(hashedPassword);
		
		 return entityManager.merge(user);
	}

	public Domainuser getUser(String login) {
		List<Domainuser> userList = entityManager
				.createNativeQuery("select *from domainuser where login = ?", Domainuser.class).setParameter(1, login)
				.getResultList();
		if (userList.size() > 0)
			return userList.get(0);
		else
			return null;
	}

}
